import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_training/model/train_entity.dart';
import 'package:ls_work/a_training/page/training_more_page.dart';
import 'package:ls_work/a_training/widgets/training_cell.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/request_url_utils.dart';
import 'package:ls_work/util/toast.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:ls_work/widgets/load_image.dart';
import 'package:ls_work/widgets/my_refresh_divider_list.dart';

class TraningPage extends StatefulWidget {
  @override
  _TraningPageState createState() => _TraningPageState();
}

class _TraningPageState extends State<TraningPage>
    with AutomaticKeepAliveClientMixin {
  int _page = 1;
  bool isMore = false;
  List<TrainInfo> trainList = [];
  List<String> imgList = [];
  List<String> titleList = [];
  List<Function()> funcList = [];
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectData();
    });
    imgList = [
      // 'home/tag_13',
      'home/tag_14', 'home/tag_15', 'home/tag_16'];
    titleList = [
      // '疫情防控',
      '院内管理', '预案制定', '应急演练'];
    funcList = [
      // () {
      //   AppNavigator.push(
      //     context,
      //     TrainingMorePage(
      //       trainingType: 'corporate_culture_train',
      //       trainingTypeName: '疫情防控',
      //     ),
      //   );
      // },
      () {
        AppNavigator.push(
          context,
          TrainingMorePage(
            trainingType: 'admission_train',
            trainingTypeName: '院内管理',
          ),
        );
      },
      () {
        AppNavigator.push(
          context,
          TrainingMorePage(
            trainingType: 'nurse_train',
            trainingTypeName: '预案制定',
          ),
        );
      },
      () {
        AppNavigator.push(
          context,
          TrainingMorePage(
            trainingType: 'care_worker_train',
            trainingTypeName: '应急演练',
          ),
        );
      }
    ];
    super.initState();
  }

  @override
  bool get wantKeepAlive => true;
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('信息发布'),
        elevation: 0.5,
      ),
      body: DeerSeparatedListView(
        padding: EdgeInsets.fromLTRB(12, 12, 12, 12),
        itemCount: 3 + trainList.length,
        itemBuilder: (_, int index) {
          switch (index) {
            case 0:
              return RequestUrlUtils.code.contains("dj")?Container(): LoadAssetImage(
                'train/t_banner',
                width: ScreenUtil.getScreenW(context),
                fit: BoxFit.cover,
              );
              break;
            case 1:
              return Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: (titleList??[]).map((e) {
                  int i = (titleList??[]).indexOf(e);
                  return GestureDetector(
                    onTap: funcList[i],
                    child: Container(
                      padding: EdgeInsets.only(bottom: 10, top: 20),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          LoadAssetImage(imgList[i]),
                          Gaps.vGap8,
                          Text(
                            e,
                            style: TextStyles.textGray16,
                          )
                        ],
                      ),
                    ),
                  );
                }).toList(),
              );
            case 2:
              return Padding(
                padding: EdgeInsets.fromLTRB(10, 15, 10, 10),
                child: Text(
                  '推荐',
                  style: TextStyles.textBoldDark18,
                ),
              );
            default:
              return Container(
                padding: EdgeInsets.fromLTRB(0, 12, 0, 12),
                child: TrainingCell(
                  info: trainList[index - 3],
                ),
              );
          }
        },
        onRefresh: _onRefresh,
        loadMore: _loadMore,
        hasMore: isMore,
        separatorBuilder: (_, int index) {
          switch (index) {
            case 0:
            case 1:
            case 2:
              return Gaps.empty;
              break;
            default:
              return Gaps.line;
          }
        },
      ),
    );
  }

  _fectData() {
    var map = {
      'recommend': 1,
      'rows': 20,
      'page': _page,
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.groupBeanList, data: map).then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            TrainListEntity model = TrainListEntity.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              isMore = (model.rows??[]).length == 20;
              setState(() {
                /// 刷新
                if (_page == 1) trainList.clear();
                trainList.addAll(model.rows??[]);
              });
            }
          } else {
            Toast.show(map["msg"]);
          }
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Future _onRefresh() async {
    _page = 1;
    _fectData();
  }

  Future _loadMore() async {
    _page++;
    _fectData();
  }
}
